<?php

declare(strict_types=1);

namespace app\admin\controller;

use app\model\NoteModel;
use support\Request;
use support\Response;

/**
 * 合作意向管理控制器
 */
class NoteController extends AdminController
{
    /**
     * 获取合作意向列表
     * 
     * @param Request $request
     * @return Response
     */
    public function index(Request $request): Response
    {
        try {
            // 获取参数
            $current = (int)$request->get('current', 1);
            $pageSize = (int)$request->get('pageSize', 10);
            $phone = $request->get('phone', '');

            // 构建查询条件
            $query = NoteModel::query();
            
            if (!empty($phone)) {
                $query->where('phone', 'like', "%{$phone}%");
            }

            // 按创建时间倒序排列
            $query->orderBy('created_at', 'desc');

            // 分页查询
            $offset = ($current - 1) * $pageSize;
            $list = $query->offset($offset)->limit($pageSize)->get();
            $total = $query->count();

            // 返回数据
            return json([
                'data' => [
                    'list' => $list,
                    'total' => $total
                ],
                'msg' => '获取成功',
                'code' => 20000
            ]);
        } catch (\Exception $e) {
            return json([
                'data' => null,
                'msg' => $e->getMessage(),
                'code' => 0
            ]);
        }
    }

    /**
     * 处理合作意向
     * 
     * @param Request $request
     * @return Response
     */
    public function process(Request $request): Response
    {
        try {
            // 参数验证
            $id = $request->post('id');
            if (empty($id)) {
                throw new \Exception('参数错误');
            }

            // 查找记录
            $note = NoteModel::find($id);
            if (!$note) {
                throw new \Exception('记录不存在');
            }

            // 检查是否已处理
            if ($note->status == 1) {
                throw new \Exception('该意向已处理');
            }

            // 更新状态
            $note->status = 1;
            $note->do_at = time();
            $note->updated_at = time();
            
            if (!$note->save()) {
                throw new \Exception('处理失败');
            }

            return json([
                'data' => null,
                'msg' => '处理成功',
                'code' => 20000
            ]);
        } catch (\Exception $e) {
            return json([
                'data' => null,
                'msg' => $e->getMessage(),
                'code' => 0
            ]);
        }
    }
} 